﻿using LayuiMvc.DataEntity.DataEntity;
using LayuiMvc.DataEntity.IdentityEntity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;

namespace LayuiMvc.DataEntity
{
    /// <summary>
    /// 数据库上下文类
    /// </summary>
    public class EFContext:IdentityDbContext<
        IdentityUserEntity,
        IdentityRoleEntity,
        int,
        IdentityUserLoginEntity,
        IdentityUserRoleEntity,
        IdentityUserClaimEntity
        >
    {
        public EFContext() : base("name=DefaultConnection")
        {
           Database.SetInitializer(new DBInitializer());
            //关闭懒加载
            Configuration.LazyLoadingEnabled = false;
        }

        /// <summary>
        /// 帖子
        /// </summary>
        public DbSet<PostEntity> Posts { get; set; }
        /// <summary>
        /// 帖子回复
        /// </summary>
        public DbSet<PostReplyEntity> PostReplys { get; set; }

        /// <summary>
        /// 帖子收藏
        /// </summary>
        public DbSet<PostCollectionEntity> PostCollections  { get; set; }

        /// <summary>
        /// 文件
        /// </summary>
        public DbSet<FileEntity> Files { get; set; }
        /// <summary>
        /// 声明
        /// </summary>
        public DbSet<IdentityClaimEntity> IdentityClaim { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUserEntity>().ToTable("IdentityUser");
            modelBuilder.Entity<IdentityRoleEntity>().ToTable("IdentityRole");
            modelBuilder.Entity<IdentityUserLoginEntity>().ToTable("IdentityUserLogin");
            modelBuilder.Entity<IdentityUserRoleEntity>().ToTable("IdentityUserRole");
            modelBuilder.Entity<IdentityUserClaimEntity>().ToTable("IdentityUserClaim");

            modelBuilder.Entity<PostEntity>()
                .HasRequired(m => m.PublishUser)
                .WithMany()
                .WillCascadeOnDelete(false);
        }

        public static EFContext Create()
        {
            return new EFContext();
        }
    }
}
